package com.hua.nailcampus.acl.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hua.nailcampus.acl.model.DynamicReply;
import com.hua.nailcampus.acl.model.vo.DynamicReplyVo;
import com.hua.nailcampus.acl.model.vo.DynamicVo;
import com.hua.nailcampus.acl.service.DynamicReplyService;
import com.hua.nailcampus.acl.service.DynamicService;
import com.hua.nailcampus.constant.RedisConst;
import com.hua.nailcampus.utils.JwtHelper;
import com.hua.nailcampus.utils.Result;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author:chenjianhua
 * @Date:2023/12/21 20:56
 * @Version 1.8
 */
@RestController
@RequestMapping("nailCampus/dynamic")
@Slf4j
public class DynamicController {

    @Autowired
    private DynamicService dynamicService;

    @Resource
    private RedisTemplate redisTemplate;

    @Autowired
    private DynamicReplyService dynamicReplyService;

    /**
     * 发布动态
     * @param dynamicVo
     * @return
     */
    @PostMapping("/publish")
    public Result publish(@RequestBody DynamicVo dynamicVo){
       dynamicVo.setResourceList(JSONObject.parseArray(dynamicVo.getFileList(),String.class));
        dynamicService.publish(dynamicVo);
        return Result.ok("发布成功");
    }

    /**
     * 获取所有动态
     * @param request
     * @return
     */
    @GetMapping("/getAllDynamic")
    public Result getAllDynamic(HttpServletRequest request){
        String token = request.getHeader("token");
        Integer userId = JwtHelper.getUserId(token);
//       判断Redis中是否有数据，若有数据则直接从缓存中拿数据
        List<DynamicVo> dynamicVoList = (List<DynamicVo>) redisTemplate.opsForValue().get(RedisConst.DYNAMIC_LISTK+userId.toString());
       if(dynamicVoList == null){
            dynamicVoList = dynamicService.getAllDynamic(userId);
       }

       return Result.ok(dynamicVoList);
    }

    @PostMapping("/replyDynamic")
    public Result sendComment(@RequestBody DynamicReply dynamicReply){
        dynamicReplyService.sendComment(dynamicReply);
        return Result.ok("评论成功");
    }

}

